import axios from 'axios'
import store from "../store";
import routes from "../routers";

// create an axios instance
const service = axios.create({
    // withCredentials: true ,//表示跨域请求时是否需要使用凭证
    baseURL: 'api',
    timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器，要是token存在，就在请求头中加入token
service.interceptors.request.use(
    config => {
        // do something before request is sent
        if (store.state.token) {
            config.headers.Authorization = store.state.token;
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
);

// response 拦截器
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        // 在status正确的情况下，code不正确则返回对应的错误信息（后台自定义为200是正确，并且将错误信息写在message），正确则返回响应
        return  response ;
    },
    error => {
        // 在status不正确的情况下，判别status状态码给出对应响应
        if (error.response) {
            console.log("在respone拦截器显示错误：", error.response)
            switch (error.response.status) {
                case 401:
                    //可能是token过期，清除它
                    // this.$store.commit("del_token");
                    store.commit("del_token");

                    routes.replace({ //跳转到登录页面
                        path: '/login',
                        // 将跳转的路由path作为参数，登录成功后跳转到该路由
                        query: {redirect: routes.currentRoute.fullPath}
                    });
            }
        }
        return Promise.reject(error.response.data);
    }
);

export default service
